package cn.smbms.controller;

import cn.smbms.pojo.Provider;
import cn.smbms.pojo.User;
import cn.smbms.service.provider.ProviderService;
import cn.smbms.service.storagerecord.StorageRecordService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.mysql.cj.util.StringUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Auther: liyuxuan
 * @Date:2021/11/7 - 11 - 07 - 19:21
 */
@Log4j
@Controller
@RequestMapping("/provider")
public class ProviderController {
    @Autowired
    private ProviderService providerService;
    @Autowired
    private StorageRecordService storageRecordService;
   /* private ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    private ProviderService providerService = (ProviderService)context.getBean("providerService");*/
    @RequestMapping("/pList")
    public String providerList(Model model, String queryProName,String queryProCode,@RequestParam(defaultValue = "1") Integer pageIndex){
        List<Provider> providerList = null;
        try {
            if(StringUtils.isNullOrEmpty(queryProName)){
                queryProName = "";
            }
            if(StringUtils.isNullOrEmpty(queryProCode)){
                queryProCode = "";
            }
            //设置页面总量
            int pageSize = Constants.pageSize;
            //总数量
            int totalCount = providerService.count(queryProName,queryProCode);
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            if (pageIndex > totalPageCount) {
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            providerList = providerService.getProviderList(queryProName,queryProCode,pageIndex,pageSize);
            model.addAttribute("providerList",providerList);
            model.addAttribute("queryProName",queryProName);
            model.addAttribute("queryProCode",queryProCode);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("供货商接口访问失败");
            return "/jsp/error";
        }
        return "/jsp/providerlist";

    }
    @GetMapping("/toAdd")
    public String toAdd(/*@ModelAttribute("provider") Provider provider*/){
        return "/jsp/provideradd";
    }
    @PostMapping("/add")
    public String add(@Valid Provider provider, BindingResult bindingResult, HttpSession session, HttpServletRequest request, @RequestParam(value = "idPic",defaultValue = "false")MultipartFile[] idPic){
        if (bindingResult.hasErrors()){
            log.debug("添加供货商失败");
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            fieldErrors.forEach(f->request.setAttribute(f.getField(),f.getDefaultMessage()));
            return "/jsp/provideradd";
        }
        String idPicPath = null;
        if(idPic.length!=0){
            String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadFiles");

            List<String> isPath = new ArrayList<>();
            for (int i = 0; i < idPic.length; i++) {
                String originalFile = idPic[i].getOriginalFilename();
                log.info("原文件名为："+originalFile);
                String prefix = FilenameUtils.getExtension(originalFile);
                log.debug("原文件后缀为："+prefix);
                if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("pneg")) {
                    String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal."+prefix;
                    log.debug("生成新的文件名称为："+fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    try {
                        idPic[i].transferTo(new File(targetFile,fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute("uploadFileError","* 上传失败");
                        return "/jsp/useradd";
                    }
                    isPath.add(File.separator + "statics" + File.separator + "uploadFiles" + File.separator + fileName);
                } else {
                    request.setAttribute("uploadFileError","* 上传图片格式不正确");
                    return "/jsp/useradd";
                }
            }

            provider.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
            provider.setCompanyLicPicPath(isPath.get(0));
            provider.setOrgCodePicPath(isPath.get(1));
            provider.setCreationDate(new Date());
            if (providerService.add(provider)) {
                return "redirect:/provider/pList";
            }

        }
        return "/jsp/provideradd";
    }
    @GetMapping("/view/{id}")
    public String view(@PathVariable String id,Model model){
        log.debug("根据ID查询供货商详情"+id);
        Provider provider = providerService.getProviderById(id);
        model.addAttribute(provider);
        return "/jsp/providerview";
    }
    @GetMapping("/toModify/{id}")
    public String toModify(@PathVariable String id,Model model){
        log.debug("根据ID查询供货商详情并修改"+id);
        Provider provider = providerService.getProviderById(id);
        model.addAttribute(provider);
        return "/jsp/providermodify";
    }
    @PostMapping("/modify")
    public String modify(Provider provider,HttpSession session){
        provider.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        provider.setModifyDate(new Date());
        if (providerService.modify(provider)) {
            return "redirect:/provider/pList";
        }
        return "/jsp/providermodify";
    }
    @ResponseBody
    @GetMapping("/delpro/{id}")
    public Object delpro(@PathVariable String id,Model model){
        if (providerService.deleteProviderById(id) > 0) {
            return model.addAttribute("delResult", "true");
        }else {
            return model.addAttribute("delResult", "false");
        }
    }
}
